package com.xiaotao.service.impl;

import com.xiaotao.entity.Coupon;
import com.xiaotao.entity.UserCoupon;
import com.xiaotao.entity.Wallet;
import com.xiaotao.mapper.CouponMapper;
import com.xiaotao.mapper.UserCouponMapper;
import com.xiaotao.mapper.WalletMapper;
import com.xiaotao.publisher.UserCouponPublisher;
import com.xiaotao.service.UserCouponService;
import com.xiaotao.util.ResponseEnum;
import com.xiaotao.util.ResponseUtil;
import com.xiaotao.util.UserUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserCouponServiceImpl implements UserCouponService {
    @Resource
    private UserCouponMapper userCouponMapper;
    @Resource
    private CouponMapper couponMapper;
    @Resource
    private WalletMapper walletMapper;
    @Resource
    private UserCouponPublisher userCouponPublisher;

    @Override
    public ResponseUtil queryAll() {
        List<UserCoupon> userCoupons = userCouponMapper.queryAll();
        return userCoupons != null ? ResponseUtil.get(ResponseEnum.OK, userCoupons) :
                ResponseUtil.get(ResponseEnum.FAIL);
    }

    @Override
    public ResponseUtil add(Integer id) throws Exception {
        Coupon coupon = couponMapper.queryById(id);
        UserCoupon userCoupon = new UserCoupon();
        userCoupon.setUserId(UserUtil.UserContext());
        userCoupon.setCouponId(id);
        userCoupon.setDiscount(coupon.getDiscount());
        userCoupon.setName(coupon.getName());
        Wallet wallet = new Wallet();
        wallet.setUserId(UserUtil.UserContext());
        Wallet wallet1 = walletMapper.queryByUserId(UserUtil.UserContext());
        if(wallet1.getPoints()<coupon.getRequiredPoints()){
           return ResponseUtil.get(ResponseEnum.FAIL,"积分不足");
        }
        wallet.setPoints(wallet1.getPoints() - coupon.getRequiredPoints());
        walletMapper.updatePoints(wallet);
        Integer add = userCouponMapper.add(userCoupon);
        userCouponPublisher.send(userCoupon.getId(),259200000);//3天后未使用过期
        return add > 0 ? ResponseUtil.get(ResponseEnum.OK) :
                ResponseUtil.get(ResponseEnum.FAIL);
    }

    @Override
    public ResponseUtil queryByUserId(Integer userId) throws Exception {
        List<UserCoupon> userCoupons = userCouponMapper.queryByUserId(userId);
        return userCoupons!=null ? ResponseUtil.get(ResponseEnum.OK,userCoupons):
                ResponseUtil.get(ResponseEnum.FAIL);
    }
}
